# Python异常处理机制演示

"""
这个文件演示了Python中各种异常处理机制，包括：

1. 1.
   基本try-except结构
2. 2.
   捕获多个异常
3. 3.
   else子句
4. 4.
   finally子句
5. 5.
   自定义异常
6. 6.
   异常链
7. 7.
   断言(assert)
8. 8.
   上下文管理器(with语句)的异常处理
9. 9.
   捕获所有异常(不推荐)
10. 10.
    重新抛出异常
    
"""

# 1. 基本try-except结构
try:
    result = 10 / 0
except ZeroDivisionError:
    print("捕获到除零错误！")

# 2. 捕获多个异常
try:
    num = int("abc")
except (ValueError, TypeError) as e:
    print(f"捕获到值错误或类型错误: {e}")

# 3. else子句(没有异常时执行)
try:
    result = 10 / 2
except ZeroDivisionError:
    print("除零错误")
else:
    print("计算成功，结果为:", result)

# 4. finally子句(无论是否异常都会执行)
try:
    f = open("nonexistent.txt", "r")
except FileNotFoundError:
    print("文件不存在")
finally:
    print("这段代码无论如何都会执行")

# 5. 自定义异常
class MyCustomError(Exception):
    def __init__(self, message):
        self.message = message

try:
    raise MyCustomError("这是我的自定义错误")
except MyCustomError as e:
    print(f"捕获到自定义错误: {e.message}")

# 6. 异常链
try:
    try:
        raise ValueError("原始错误")
    except ValueError as e:
        raise RuntimeError("二次错误") from e
except RuntimeError as e:
    print(f"捕获到运行时错误: {e}")
    print(f"原始错误原因: {e.__cause__}")

# 7. 断言(assert)
def divide(a, b):
    assert b != 0, "除数不能为零"
    return a / b

try:
    print(divide(10, 0))
except AssertionError as e:
    print(f"断言失败: {e}")

# 8. 上下文管理器(with语句)处理异常
try:
    with open("example.txt", "w") as f:
        f.write("Hello")
        # 这里如果发生异常，文件会被正确关闭
        result = 10 / 0
except ZeroDivisionError:
    print("在with块中发生了除零错误")

# 9. 捕获所有异常(不推荐)
try:
    unknown_operation()
except Exception as e:
    print(f"捕获到未知错误: {type(e).__name__}: {e}")

# 10. 重新抛出异常
try:
    try:
        result = 10 / 0
    except ZeroDivisionError:
        print("捕获到错误并重新抛出")
        raise  # 重新抛出当前异常
except ZeroDivisionError:
    print("外层捕获到重新抛出的错误")